package com.mo.security.handler;

import com.alibaba.fastjson2.JSON;
import com.mo.common.Result;
import com.mo.entity.User;
import com.mo.security.entity.LoginUser;
import com.mo.service.UserService;
import com.mo.utils.JWTConstant;
import com.mo.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class JwtOncePerRequestFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        token = token.replace(JWTConstant.JWT_TOKEN_PREFIX, "");
        String userId = null;
        try {
            if (jwtUtils.validateToken(token)) {
                userId = jwtUtils.getSubject(token);
            }
        } catch (Exception e) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(Result.error("token有误，请重新登录", HttpServletResponse.SC_BAD_REQUEST)));
            return;
        }

        // 重新查找用户信息，并设置到 SecurityContextHolder 中
        User user = userService.getById(userId);
        String[] auths = userService.getUserAuthorityById(userId);
        System.out.println("================================权限列表===================================");
        System.out.println(Arrays.toString(auths));
        System.out.println("================================权限列表===================================");
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(auths);
        LoginUser loginUser = new LoginUser(user, authorityList);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, authorityList);
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}